import React, { useContext, useMemo, type ComponentType } from "react";
import { useVirtualScroll } from "../hooks/use-virtual-scroll";
import type { FlattenedTask } from "../types";
import { GanttConsts } from "../constants";
import GanttContext from "../context";

export interface RenderItemProps {
  task: FlattenedTask;
  index: number;
}

interface VirtualListProps {
  items: FlattenedTask[];
  Comp: ComponentType<RenderItemProps>;
  className?: string;
}

const VirtualList: React.FC<VirtualListProps> = ({
  items,
  Comp,
  className = "",
}) => {
  const {
    startIndex,
    offsetY,
    totalHeight,
    visibleItems,
    handleScroll,
    handleWheel,
    ganttContainerRef,
  } = useVirtualScroll({
    items,
  });
  const { containerHeight } = useContext(GanttContext)

  // 使用useMemo缓存渲染项目，减少重新渲染
  const renderedItems = useMemo(() => {
    return visibleItems.map((item, index) => {
      const actualIndex = startIndex + index;
      return (
        <div
          key={item.id}
          style={{
            height: GanttConsts.ITEM_HEIGHT,
          }}
        >
          <Comp task={item} index={actualIndex} />
        </div>
      );
    });
  }, [visibleItems, startIndex, Comp]);

  return (
    <div
      className={`relative overflow-hidden ${className}`}
      style={{
        height: `${containerHeight - GanttConsts.HEADER_HEIGHT - GanttConsts.HEAD_HEIGHT}px`,
      }}
      ref={ganttContainerRef}
      onScroll={handleScroll}
      onWheel={handleWheel}
    >
      {/* 创建一个占位容器来维持总高度 */}
      <div style={{
        height: totalHeight,
        position: "relative",
        contain: "layout style paint", // 优化渲染性能
      }}>
        {/* 渲染可见项目容器，使用transform偏移 */}
        <div
          style={{
            transform: `translateY(${offsetY}px)`,
            willChange: "transform",
          }}
        >
          {renderedItems}
        </div>
      </div>
    </div>
  );
};

export default VirtualList;
